import { fileURLToPath } from 'url';
import { dirname } from 'path';
import log4js from 'log4js';
import path from 'path';
import fs from 'fs';
import innerDayjs from 'dayjs';
import { env } from 'node:process'
const tmpDir = path.join(path.resolve(), 'tmp');
env.TZ = 'Asia/Shanghai'
// 配置 log4js
log4js.configure({
    appenders: {
        console: { type: 'console' }, // 设置控制台输出的日志记录器
        file: { type: 'file', filename: 'app.log' } // 设置文件输出的日志记录器
    },
    categories: {
        default: { appenders: ['console', 'file'], level: 'info' } // 设置默认的类别
    }
});

export function getDirName(importMetaUrl) {
    const __filename = fileURLToPath(importMetaUrl);
    const __dirname = dirname(__filename);
    return __dirname;
}

export const debounce = function (func, wait = 1000) {
    let startTime = Date.now();
    let timer;

    return (...args) => {
        if (Date.now() - startTime < wait && timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func(...args);
        }, wait);
        startTime = Date.now();
    };
};

export const throttle = function (func, delay = 1000) {
    let lastTime = 0;
    return (...args) => {
        const nowTime = new Date().getTime();
        if (nowTime - lastTime > delay) {
            func.apply(this, args);
            lastTime = nowTime;
        }
    };
};

export const converterTree = (
    treeData,
    converterFunc = (e) => e,
    childName = 'children',
    sortFunc = (a, b) => 0
) => {
    if (!treeData) return null;
    const treeDataList = [...(treeData || [])];
    return treeDataList
        .map((dataItem) => {
            const converItem = converterFunc(dataItem);
            if (converItem) {
                converItem[childName] = converterTree(
                    dataItem?.[childName],
                    converterFunc,
                    childName,
                    sortFunc
                );
            }
            return converItem;
        })
        .sort(sortFunc);
};

export const listToTree = (list, idKey, parentKey) => {
    let map = {}, tree = [], i;

    // 初始化每个节点，并建立一个map，以id为key，节点引用为值。
    for (i = 0; i < list.length; i++) {
        map[list[i][idKey]] = list[i];
        list[i].children = []; // 初始化children数组
    }

    for (i = 0; i < list.length; i++) {
        let node = list[i];
        if (node[parentKey]) {
            // 如果存在父节点
            if (map[node[parentKey]]) {
                // 如果父节点在map中
                map[node[parentKey]].children.push(node);
            } else {
                // 没有找到父节点的情况，可能需要根据实际情况处理，这里直接添加到树的根部
                tree.push(node);
            }
        } else {
            // 没有父节点，是树的根
            tree.push(node);
        }
    }

    return tree;
}

export const tileTree = (treeData, childName = 'children') => {
    return treeData.reduce((result, node) => {
        result.push(node);
        if (node[childName]) {
            result.push(...tileTree(node[childName], childName));
        }
        return result;
    }, []);
};


export const filterTree = (treeArray, filterFn, childrenKey = 'children') => {
    return treeArray.map(tree => filterTreeNode(tree, filterFn, childrenKey)).filter(tree => tree !== null);
}

function filterTreeNode(node, filterFn, childrenKey) {
    // 如果节点有子节点，递归过滤子节点
    if (node[childrenKey] && node[childrenKey].length > 0) {
        node[childrenKey] = node[childrenKey].map(childNode => filterTreeNode(childNode, filterFn, childrenKey)).filter(child => child !== null);
    }

    // 如果节点通过筛选函数，或者它有子节点（经过过滤后可能为空），则保留节点
    if (filterFn(node) || (node[childrenKey] && node[childrenKey].length > 0)) {
        return node;
    }

    // 否则，移除节点
    return null;
}

/**
 * 保存文件到本地临时目录
 */
export const saveBufferToLocal = async (fileName, fileBuffer) => {
    const fileDir = path.join(tmpDir, `${new Date().getTime()}`);
    fs.mkdirSync(fileDir, { recursive: true });
    const filePath = path.join(fileDir, fileName);
    fs.writeFileSync(filePath, fileBuffer);
    return filePath;
}

export const dayjs = innerDayjs;

export const logger = log4js.getLogger();